<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use app\service\billService;
use app\service\repairService;
use app\service\roominfoService;
use app\service\homeService;
use app\service\apiService;
use app\service\apixcxService;
use app\service\appletService;
use think\Db;
use think\Controller;
use printing\printDemo;
use app\service\xcxService;
use app\service\lifeapiService;
use app\service\apiinvoiceService;
use think\Request;
use think\Log;
class H5alipay2 extends Base{
	public function test()
	{
		session("url",request()->url());
	}
	//验证姓名
	public function checkname(){
		if(request()->isPost())
		{
			$data=request()->post();
			$roominfo=Db::table("roominfo")->where("id",$data["room_id"])->find();
			
			if(strpos($roominfo["owner_name"],$data["owner_name"])!== false){
				$roominfo_user=Db::table("roominfo_user")->where("user_id",session("user_id"))->where("room_id",$data["room_id"])->find();
				/*$url=url("billinfo_discount")."?id=".$roominfo["id"];
				echo "<script>location.href='$url';</script>";
				exit;*/
				if(empty($roominfo_user))
				{
					$communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
					$info["user_id"]=session("user_id");
					$info["room_id"]=$data["room_id"];
					$info["community_id"]=$roominfo["community_id"];
					$info["community_name"]=$communityinfo["community_name"];
					$info["address"]=$roominfo["address"];
					$info["create_time"]=time();
					$res=Db::table("roominfo_user")->insert($info);
				}
				$url=url("billinfo")."?id=".$roominfo["id"];
				echo "<script>location.href='$url';</script>";
				exit;
				
			}else{
				echo "<script>alert('验证失败');history.go(-1);</script>";
				exit;
			}
		}else{
			$id=request()->get("id");
			$roominfo_user=Db::table("roominfo_user")->where("user_id",session("user_id"))->where("room_id",$id)->find();
			if(!empty($roominfo_user)){
				$url=url("billinfo")."?id=".$id;
				echo "<script>location.href='$url';</script>";
				exit;
			}
			$roominfo=Db::table("roominfo")->where("id",$id)->find();
			if(mb_strlen($roominfo["owner_name"])=="1"){
				$url=url("billinfo")."?id=".$roominfo["id"];
				echo "<script>location.href='$url';</script>";
				exit;
			}
			if(empty($roominfo["owner_name"])){
				$url=url("billinfo")."?id=".$roominfo["id"];
				echo "<script>location.href='$url';</script>";
				exit;
			}
			$roominfo["owner_name"]=str_repeat('*', mb_strlen($roominfo['owner_name'])-1).mb_substr($roominfo["owner_name"],-1);
			$this->assign("roominfo",$roominfo);
			return $this->fetch("check_name");
		}
		
	}
	public function selectroom(){
		//session("url",request()->url());
		/*$roominfo_user=Db::table("roominfo_user")->where("user_id",session('user_id'))->find();
		if(!empty($roominfo_user))
		{
			$url=url("H5alipay/billinfo_discount")."?id=".$roominfo_user["room_id"];
			echo "<script>location.href='$url';</script>";
			exit;
		}*/
		$community_id=request()->get("community_id");
		$communityinfo=Db::table("community")->where("id",$community_id)->find();
		if(empty($communityinfo)){
		    return "小区信息错误";
			$this->error("小区信息错误");
		}
		$this->assign("communityinfo",$communityinfo);

		$group = (new xcxService())->groupList($communityinfo["community_id"]);
		
		$str="[";
		foreach ($group as $key => $value) {
			$str=$str."'".$value."',";
		}
		$str=$str."]";
		
		$this->assign("str",$str);
		return $this->fetch();
	}
    
    public function getgroup(){
		$community_id = request()->param('community_id');
        $communityinfo=Db::table("community")->where("community_name",$community_id)->find();
        $community_id=$communityinfo["id"];
        $group = (new xcxService())->groupList($community_id);
        sort($group ,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $group ;
	}
    
	public function getbuilding(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = (new xcxService())->buildingList($group,$community_id);
        sort($building,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $building;
	}
	public function getunit(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = (new xcxService())->unitList($building,$group,$community_id);
        sort($unit,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $unit;
	}
	public function getroom(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = (new xcxService())->roomList($unit,$building,$group,$community_id);
        sort($room,SORT_NATURAL|SORT_STRING|SORT_FLAG_CASE);
        return $room;
	}

	public function getroominfo(){
		$community_id = request()->param('community_id');
        $group = request()->param('group');;
        $building = request()->param('building');
        $unit = request()->param('unit');
        $room = request()->param('room');
        $roominfo=(new xcxService())->getroominfo($community_id,$group,$building,$unit,$room);
        if(empty($roominfo)){
        	$arr["errorCode"]="1";
        	$arr["errorMsg"]="请选择房屋";
        	echo json_encode($arr);
        	exit;
        }else{
        	$arr["errorCode"]="0";
        	$arr["roominfo"]=$roominfo;
        	echo json_encode($arr);
        	exit;
        }
	}

	public function billinfo(){
		session("url",request()->url());
		$id=request()->get("id");
		$roominfo=Db::table("roominfo")->where("id",$id)->find();
		$communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
		
		$roominfo["community_name"]=$communityinfo["community_name"];

		 //根据房号查询账单
        $billlis = (new appletService())->billRoomIdList($roominfo['out_room_id']);
        if(empty($billlis)){
			return $this->fetch("nopaymsg");
		}
		//查询缴费类型
		$costtype = (new appletService())->cost_type($roominfo['out_room_id']);
		$billsum=(new appletService())->billsum($roominfo['out_room_id']);
		$billlist=array();
        foreach ($costtype as $b){
        	$arr["costtype"]=$b;
            $billinfo = (new appletService())->cost_type_bill($roominfo['out_room_id'],$b);
            $arr["billinfo"]=$billinfo;
            $billlist[]=$arr;
        }
        
		/*echo "<pre>";
		var_dump($billlist);
		die;*/
		$this->assign("billsum",$billsum);
		$this->assign("billlist",$billlist);
		$this->assign("roominfo",$roominfo);
		return $this->fetch();
	}



	//计算要缴费的金额
	public function moneysum(){
		$post=request()->post();
		$ordermoney=0;
		if(!(request()->has('billid'))){
			return json(['state'=>'1','info' => "0"]);
		}
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			$ordermoney=$ordermoney+$billinfo["bill_entry_amount"];
		}
		$data["order_money"]=$ordermoney;
		
		
		$data["pay_money"]=round($data["order_money"],2);
		return json(['state'=>'1','info' => $data["pay_money"]]);
	}

	public function createOrder(){
		if(!(request()->has('billid'))){
			return json(['info' => '请选择要交费的账单']);
		}
		$post=request()->post();
		$billpay["billid"]=serialize($post["billid"]);
		
		$ordermoney=0;
		$subjectremark="";
		foreach ($post["billid"] as $key => $value) {
			$billinfo=Db::table("bill")->where('id',$value)->find();
			if($billinfo["status"]=="TRADE_SUCCESS"){
				return json(['info' => '该帐单已缴费']);
			}
			$ordermoney=$ordermoney+$billinfo["bill_entry_amount"];
			
			$subjectremark=$subjectremark.$billinfo["cost_type"].":".$billinfo["bill_entry_amount"]."元| ";
		}
		$billpay["order_money"]=$ordermoney;
		$billpay["user_id"]=session("user_id");
		
		$billpay["out_room_id"]=$post["out_room_id"];
		$billpay["room_address"]=$post["room_address"];
		$billpay["community_id"]=$post["community_id"];
		$billpay["community_name"]=$post["community_name"];
		
		$billpay["pay_money"]=round($billpay["order_money"],2);
		$billpay["out_trade_no"]=date('YmdHiss').rand(100000,999999);

		$token = (new xcxService())->token($billpay["community_id"]);
        $subject = $billpay["community_name"].$billpay["room_address"].$subjectremark.'已缴费';
        $api = new lifeapiService();
         
            
       
        $notifyUrl="https://www.wuye.zfbzhsq.com/admin/callback/alinotice";
        $result = $api->orderCreate(json_encode(['out_trade_no'=> $billpay["out_trade_no"],'total_amount'=>$billpay["pay_money"],'buyer_id'=>$billpay["user_id"],'subject' =>$subject,'token'=>$token ,'notifyurl'=>$notifyUrl]));
		if(property_exists($result,'sub_msg')){	
			return json(['info' => $result->sub_msg]);
		}else{
			$billpay['trade_no'] =  $result->trade_no;
			
			$billpay["scenes"]=3;	
			$billpay["subject"]=$subject;
			$res=Db::table("billpay")->insert($billpay);
			//返回结果到前台唤起收银台
			if($res){
				return json(['order_no' => $billpay['trade_no']]);
			}else{
				return json(['info' => '订单存储失败']);
			}
		}	
	}


}